package com.caizi.socket.imagetool;

import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class ExcelOper {

    public static void writeSheet(File destSheet, Map<String, File> imagesMap) throws IOException, Exception {
        WritableWorkbook wwb = null;
        Workbook wb = null;
        try {
            wb = Workbook.getWorkbook(destSheet);
            File newFile = new File(destSheet.getParent() + File.separator + "处理后_" + destSheet.getName());
            wwb = Workbook.createWorkbook(newFile, wb);
            WritableSheet ws = wwb.getSheet(0);
            ws.setColumnView(1, 20);
            Cell[] cells = ws.getColumn(0);
            for (int i = 0; i < cells.length; i++) {
                String product = cells[i].getContents();
                File image = imagesMap.get(product);
                if (null == image) {
                    continue;
                }
                Image src = javax.imageio.ImageIO.read(image); // 构造Image对象
                int wideth = src.getWidth(null); // 得到源图宽
                int height = src.getHeight(null); // 得到源图长
                ws.setRowView(i + 1, 2000 * height / wideth);
                WritableImage wi = new WritableImage(cells[i].getColumn() + 1, cells[i].getRow(), 1, 1, imagesMap.get(product));
                ws.addImage(wi);
            }
            wwb.write();
            System.out.println("已将图片更新至：" + newFile.getAbsolutePath() + "中!");
        } catch (Exception e) {
            throw e;
        } finally {
            wb.close();
            wwb.close();
        }
    }

    public static List<String> readSheet(File destSheet) throws Exception {
        List<String> productIds = new ArrayList<String>();
        Workbook wb = null;
        try {
            wb = Workbook.getWorkbook(destSheet);
            Sheet sheet = wb.getSheet(0);
            Cell[] cells = sheet.getColumn(0);
            for (Cell cell : cells) {
                productIds.add(cell.getContents());
            }
        } catch (Exception e) {
            throw e;
        } finally {
            wb.close();
        }
        return productIds;
    }
}
